package com.lsk.netdisk.file.authz;

import com.lsk.netdisk.file.helpers.CloudHelper;
import com.lsk.netdisk.file.helpers.FileHelper;
import com.lsk.netdisk.file.mappers.DirsMapper;
import com.lsk.netdisk.file.mappers.SpaceMapper;
import com.lsk.netdisk.file.model.Dir;
import com.lsk.netdisk.file.model.Space;
import com.lsk.netdisk.file.utils.FileSizeUtil;
import com.lsk.netdisk.file.utils.SpringUtil;
import org.springframework.web.multipart.MultipartFile;

public class Authz {

	private static SpaceMapper spaceMapper = SpringUtil.getBean(SpaceMapper.class);
	private static DirsMapper dirsMapper = SpringUtil.getBean(DirsMapper.class);
	private static CloudHelper cloudHelper = SpringUtil.getBean(CloudHelper.class);

	public static boolean checkSpace(MultipartFile file, Integer uid){
		Space space = spaceMapper.querySpaceInformationByUserId(uid);
		double available = space.getTotal().doubleValue() - space.getUsed();
		double fileSize = FileSizeUtil.FormatFileSize(file.getSize(),FileSizeUtil.SIZETYPE_MB);
		return available > fileSize;
	}
	public static boolean checkPermission(Integer dirID,Integer uid, String token){
		Dir dir = dirsMapper.queryDirById(dirID);
		Permission permission = Permission.valueOf(dir.getPermission());
		switch(permission){
			case All:
				return true;
			case Owner:
				return dir.getOwnerID().equals(uid);
			case Admin:
				return cloudHelper.isAdmin(token);
			default:
				throw new RuntimeException("Unknown permission: "+permission);
		}
	}
}
